import store from '@/store'
import axios from 'axios'
import router from '@/router'
import { Toast } from 'vant'

const request = axios.create({
  baseURL: 'http://geek.itheima.net/'
})

// 添加请求拦截器
request.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    if (store.state.tokenObj.token) {
      config.headers.Authorization = 'Bearer ' + store.state.tokenObj.token
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)
// 添加响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  async error => {
    if (error.response.status == 401) {
      try {
        const res = await axios({
          url: 'http://geek.itheima.net/v1_0/authorizations',
          method: 'put',
          headers: {
            Authorization: 'Bearer ' + store.state.tokenObj.refresh_token
          }
        })
        store.commit('setToken', {
          token: res.data.data.token,
          refresh_token: store.state.tokenObj.refresh_token
        })
        return request(error.config)
      } catch {
        Toast.fail('登录状态已失效，请重新登录')
        router.push('/login')
        setTimeout(() => {
          console.clear()
        }, 500)
      }
    } else {
      return Promise.reject(error)
    }
  }
)

export default request
